<template>
  <div class="page">
    <nav-bar title="网格巡查" border></nav-bar>
    <div class="page-main" style="margin-top: 44px">
      <van-sticky class="page-scroll" :offset-top="44">
        <van-form
          validate-trigger="onSubmit"
          :show-error="false"
          ref="from"
          input-align="right"
          error-message-align="right"
          :label-width="120"
          @failed="onFailed"
          @submit="onSubmit"
        >
          <van-field
            readonly
            label-class="van-cell__title_gray"
            v-model="inspectionDetail.name"
            label="巡查点名称"
            right-icon="arrow"
            class="van-field__right-icon-white"
          />
          <van-field
            readonly
            label-class="van-cell__title_gray"
            v-model="inspectionDetail.content"
            label="巡查点要求"
            right-icon="arrow"
            class="van-field__right-icon-white"
          />
          <van-field
            required
            readonly
            clickable
            name="inspectionResultName"
            v-model="formParams.inspectionResultName"
            label="巡查结果"
            placeholder="请选择"
            right-icon="arrow"
            :rules="rules.inspectionResultName"
            @click="dictOpenPopup('inspectionResult')"
          />
          <template v-if="formParams.inspectionResult === '1'">
            <van-field required label="异常说明" readonly :border="false" />
            <van-field
              required
              name="abnormal"
              v-model="formParams.abnormal"
              placeholder="请输入巡查点位时遇到的问题"
              rows="5"
              autosize
              type="textarea"
              show-word-limit
              :border="false"
              input-align="left"
              class="van-field__value--textarea"
              maxlength="200"
              :rules="rules.abnormal"
            />
          </template>
          <van-field label="现场照片/视频" readonly :border="false">
            <template #input>
              <van-radio-group v-model="accept" direction="horizontal">
                <van-radio name="image/*">照片</van-radio>
                <van-radio name="video/*">视频</van-radio>
              </van-radio-group>
            </template>
          </van-field>
          <van-field class="van-field__value--upload" input-align="left" :border="false">
            <template #input>
              <van-uploader
                name="fileList"
                v-model="fileList"
                max-count="9"
                capture="camera"
                :accept="accept"
                :max-size="maxSize"
                :preview-image="previewImage"
                :before-read="uploadBeforeRead"
                :after-read="uploadAfterRead"
                @click-preview="previewClick"
              >
                <template #preview-cover="file">
                  <template v-if="format.includes(file.file.name.split('.')[file.file.name.split('.').length - 1])">
                    <div class="van-uploader__preview-masker"></div>
                    <video-player
                      class="video-player vjs-custom-skin"
                      :playsinline="true"
                      :options="{
                        aspectRatio: '16:16',
                        sources: [
                          {
                            src: $config.ImageURl + file.file.url
                          }
                        ]
                      }"
                    ></video-player>
                  </template>
                </template>
                <div class="van-uploader__input--white">
                  <div class="van-uploader__input--content">
                    <div class="upload-image">
                      <img src="@/assets/images/basic/icon_camera@2x.png" />
                    </div>
                    <div class="upload-text">点击拍摄</div>
                  </div>
                </div>
              </van-uploader>
            </template>
          </van-field>
          <div style="padding: 0 16px" align="right">
            <van-button type="info" size="mini" native-type="button" @click="onEventReport">事件上报</van-button>
          </div>
          <div style="margin: 60px 16px">
            <van-row :gutter="23">
              <van-col span="12">
                <van-button block native-type="button" @click="onClear">清空</van-button>
              </van-col>
              <van-col span="12">
                <van-button block type="info" native-type="submit" :disabled="buttonDisabled">提交</van-button>
              </van-col>
            </van-row>
          </div>
        </van-form>
      </van-sticky>
    </div>
    <!-- 字典项 -->
    <van-popup v-model="dictPopupShow" round position="bottom" @close="dictValue = ''">
      <van-picker
        show-toolbar
        :default-index="dictData[dictType] && dictData[dictType].findIndex(o => o.code === dictValue)"
        :columns="dictData[dictType]"
        value-key="description"
        @cancel="dictPopupShow = false"
        @confirm="dictOnConfirm"
        @change="dictOnChange"
      />
    </van-popup>
    <!-- 视频预览 -->
    <gb-video :url="videoUrl" :show.sync="videoPopupShow"></gb-video>
  </div>
</template>
<script>
import InspectVisit from '@/api/inspectVisit'
import Upload from '@/mixins/upload'
import SelectPopup from '@/mixins/selectPopup'
import { formatTimes } from '@/libs/tool'
import mapPlugin from '@/libs/mapPlugin'
class FormParams {
  constructor() {
    // 网格编码
    this.gridCode = ''
    // 网格巡查编码
    this.inspectionRecordCode = ''
    // 巡查点编码
    this.inspectionPointCode = ''
    // 巡查结果
    this.inspectionResult = ''
    this.inspectionResultName = ''
    // 异常描述
    this.abnormal = ''
    // 图片
    this.imageUrl = ''
  }
}
export default {
  mixins: [Upload, SelectPopup],
  data() {
    return {
      folder: 'inspection/grid',
      accept: 'image/*',
      maxSize: 50 * 1024 * 1024,
      fileList: [],
      format: ['mp4', 'avi', 'mov'],
      videoPopupShow: false,
      videoUrl: '',
      dictTypes: 'inspectionResult',

      inspectionDetail: {},
      formParams: new FormParams(),
      rules: {
        inspectionResultName: [{ required: true, message: '请选择巡查结果' }],
        abnormal: [{ required: true, message: '请输入异常说明' }]
      },
      buttonDisabled: false,

      goEventReportFlag: false
    }
  },
  created() {
    // 字典项
    this.getDict(this.dictTypes)
    this.getDetail()
  },
  methods: {
    getDetail() {
      InspectVisit.Grid.detail({
        inspectionPointCode: this.$route.query.inspectionPointCode,
        date: this.$route.query.date || formatTimes.formatDate(new Date())
      }).then(res => {
        const { status, data } = res.data
        if (status === 0) {
          this.inspectionDetail = data
        }
      })
    },
    dictOnChange() {
      if (this.dictType === 'inspectionResult') this.formParams.abnormal = ''
    },
    // 视频预览
    previewClick({ file }, detail) {
      const urlArr = this.fileList[detail.index].url.split('.')
      const suffix = urlArr[urlArr.length - 1]
      if (this.format.includes(suffix)) {
        this.videoPopupShow = true
        this.videoUrl = this.$config.ImageURl + this.fileList[detail.index].url
      }
    },
    // 表单 - 校验
    onFailed(errorInfo) {
      this.$refs.from.scrollToField(errorInfo.errors[0].name)
    },
    // 表单 - 提交
    onSubmit() {
      this.formParams.gridCode = this.$route.query.gridCode
      this.formParams.inspectionRecordCode = this.inspectionDetail.inspectionRecord.code
      this.formParams.inspectionPointCode = this.$route.query.inspectionPointCode
      this.formParams.imageUrl = this.fileList.map(o => o.url).join(',')
      this.buttonDisabled = true
      InspectVisit.Grid.save(this.formParams)
        .then(res => {
          const { status } = res.data
          if (status === 0) {
            this.$toast.success('提交成功')
            if (this.goEventReportFlag) {
              this.goEventReport()
            } else {
              this.$router.go(-1)
            }
          } else {
            this.$toast.fail(res.data.message)
          }
          this.buttonDisabled = false
        })
        .catch(() => {
          this.buttonDisabled = false
        })
    },
    onClear() {
      this.$dialog
        .confirm({
          title: '提示',
          message: '是否清空所有内容',
          confirmButtonText: '是',
          cancelButtonText: '否'
        })
        .then(() => {
          this.formParams = new FormParams()
        })
    },
    // 事件上报
    onEventReport() {
      this.$dialog
        .confirm({
          title: '提示',
          message: '是否提交巡查结果',
          confirmButtonText: '是',
          cancelButtonText: '否'
        })
        .then(() => {
          this.goEventReportFlag = true
          this.$refs.from.submit()
        })
        .catch(() => {
          this.goEventReport()
        })
    },
    // 事件上报 - 跳转
    goEventReport() {
      mapPlugin.geocoder([this.inspectionDetail.longitude, this.inspectionDetail.latitude], result => {
        this.$router.push({
          name: 'event-report',
          params: {
            eventLocation: result.regeocode.formattedAddress,
            eventDescription: this.formParams.abnormal,
            fileList: this.fileList
          }
        })
      })
    }
  }
}
</script>
